package com.grantz.function.bbs.core.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.grantz.function.bbs.core.entity.Group;
import com.grantz.function.bbs.core.inter.GroupService;
import com.grantz.function.bbs.core.jpa.GroupJPA;
import com.grantz.model.bbs.GroupModel;
import com.grantz.model.bbs.GroupSearch;
import com.grantz.models.base.element.page.ElementPage;

@Service
public class GroupServiceImpl implements GroupService{

	@Autowired
	private GroupJPA dao;

	@Override
	public Group save(Group entity) {
		return dao.save(entity);
	}

	@Override
	public Optional<Group> findOneById(String id) {
		return dao.findById(id);
	}

	@Override
	public ElementPage<GroupModel> queryElementPage(GroupSearch query) throws Exception {
		Page<Group>  page = queryPage(query);
		return new ElementPage<GroupModel>(popModel(page.getContent()), page.getTotalElements(), page.getNumber(), page.getSize());
	}

	private  List<GroupModel>  popModel(List<Group>  entityList){
		List<GroupModel>  rt = new ArrayList<GroupModel>();
		for(Group  entity : entityList) {
			  rt.add(popOne(entity));
		}
		return rt;
	}

	@Override
	public  GroupModel  popOne(Group  group) {
		GroupModel model =  new GroupModel();
		model.setId(group.getId());
		model.setGroupName(group.getGroupName());
		model.setGroupDesc(group.getGroupDesc());
		model.setLongitude(group.getLongitude());
		model.setLatitude(group.getLatitude());
		model.setBigType(group.getBigType());
		model.setMidType(group.getMidType());
		return model;
	}

	@Override
	public Page<Group> queryPage(GroupSearch model) throws Exception {
		PageRequest pageable = PageRequest.of(model.getPageNo(), model.getPageSize());
		Specification<Group> specifications = new Specification<Group>() {

			private static final long serialVersionUID = 1L;

			@Override
			public Predicate toPredicate(Root<Group> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
				List<Predicate> list = new ArrayList<Predicate>();
//				if(StringUtil.isNotEmpty(model.getWechatno())) {
//					Predicate pred = criteriaBuilder.like(root.get("wechatNo").as(String.class), "%"+model.getWechatno()+"%");
//					list.add(pred);
//				}
				Predicate[] p = new Predicate[list.size()];
				return criteriaBuilder.and(list.toArray(p));
			}
		};
		return dao.findAll(specifications, pageable);
	}

}
